<script setup lang="tsx">
import { computed, reactive, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { menuAdd, menuGet, menuUpdate } from '@/service/api/sys-menu';

defineOptions({
  name: 'MenuOperateModal'
});

export type OperateType = NaiveUI.TableOperateType | 'addChild';

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: Api.SystemManage.Menu | null;
}

const menuOptions = [
  {
    value: '1',
    label: '菜单'
  },
  {
    value: '2',
    label: '按钮'
  }
];

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.menu.addMenu'),
    addChild: $t('page.manage.menu.addChildMenu'),
    edit: $t('page.manage.menu.editMenu')
  };
  return titles[props.operateType];
});

type Model = Pick<Api.SystemManage.Menu, 'id' | 'pid' | 'name' | 'type' | 'auth' | 'url' | 'sort' | 'remark'> & {
  pName: string;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    pName: '根菜单',
    id: '',
    pid: '0',
    type: '1',
    name: '',
    auth: '',
    url: '',
    sort: 0,
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'auth' | 'url'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  url: defaultRequiredRule,
  auth: defaultRequiredRule
};

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (!props.rowData) return;

  if (props.operateType === 'addChild') {
    const { id, name } = props.rowData;

    Object.assign(model, { pid: id, pName: name });
  }

  if (props.operateType === 'edit') {
    menuGet(props.rowData).then(({ error, data }) => {
      if (!error) {
        Object.assign(model, props.rowData);
        if (data.parent) {
          model.pName = data.parent.name;
        }
      }
    });
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add' || props.operateType === 'addChild') {
    const { error } = await menuAdd(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
    }
  }
  if (props.operateType === 'edit') {
    const { error } = await menuUpdate(model);
    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
    }
  }

  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

watch(
  () => model.url,
  val => {
    if (val.startsWith('/')) {
      model.auth = `${val.substring(1, val.length).replace('/', '-')}`;
    } else if (val.endsWith('/')) {
      model.auth = `${val.substring(0, val.length - 1).replace('/', '-')}`;
    } else {
      model.auth = `${val.replace('/', '-')}`;
    }
  }
);
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="上级菜单" path="pName">
          <NInput v-model:value="model.pName" readonly />
        </NFormItem>
        <NFormItem :label="$t('page.manage.menu.menuType')" path="type">
          <NRadioGroup v-model:value="model.type">
            <NRadio v-for="item in menuOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
        <NFormItem label="名称" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.manage.menu.form.menuName')" />
        </NFormItem>
        <NFormItem label="Url地址" path="url">
          <NInput v-model:value="model.url" placeholder="请输入Url地址" />
        </NFormItem>
        <NFormItem label="路由权限" path="auth">
          <NInput v-model:value="model.auth" disabled placeholder="请输入路由权限" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.menu.order')" path="sort">
          <NInputNumber v-model:value="model.sort" class="w-full" :placeholder="$t('page.manage.menu.form.order')" />
        </NFormItem>

        <NFormItem label="备注" path="remark">
          <NInput v-model:value="model.remark" type="textarea" class="w-full" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end" :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
